import pRight from '@/images/common/rightIn.png';
import utils from '@/utils';
import { debounce } from '@/utils/helper.js';
import { Image, ScrollView, View } from '@tarojs/components';
import Taro from '@tarojs/taro';
import React, { useEffect, useState } from 'react';
import './index.scss';

const ProductClassificationItem = ({ productGroup, onClick }) => {
  return (
    <View className="level-wrap">
      <View
        className="level1"
        onClick={() => {
          onClick(productGroup);
        }}
      >
        <View className="txt">{productGroup.name}</View>
        <Image className="right-icon" src={pRight} />
      </View>

      {productGroup.secondGroupList?.length > 0 && (
        <View className="level2-wrap">
          {productGroup.secondGroupList?.map((item) => {
            const { id, name } = item;
            return (
              <View
                key={id}
                className="level2"
                onClick={() => {
                  onClick(item);
                }}
              >
                <View className="txt omit">{name}</View>
              </View>
            );
          })}
        </View>
      )}
    </View>
  );
};

const ProductClassification = ({ productGroups, merchantId, orgId, shopName }) => {
  const handleClick = ({ id }) => {
    Taro.navigateTo({
      url: `/mainSubPack/shopProductFilter/index?groupId=${id}&merchantId=${merchantId}&orgId=${orgId}&shopName=${encodeURIComponent(
        shopName,
      )}`,
    });
  };

  const [pagination, setPagination] = useState({ page: 1, pageSize: 20, finished: true });

  useEffect(() => {
    if (productGroups?.length) {
      setPagination({ ...pagination, page: 1, finished: false });
    }
  }, [productGroups]);

  // 滚动获取
  const handleScrollToLower = debounce(() => {
    const { page, pageSize, finished } = pagination;

    if (page * pageSize > productGroups?.length) {
      if (!finished) {
        setPagination({ ...pagination, finished: true });
      }
      return;
    }

    setPagination({ ...pagination, page: page + 1, finished: false });
  }, 500);

  return (
    <ScrollView
      className="ProductClassification"
      enableFlex
      scrollY
      style={{
        height: utils.getCalcHeight({}, 321),
      }}
      lowerThreshold={200}
      onScrollToLower={handleScrollToLower}
    >
      {productGroups?.slice(0, pagination.page * pagination.pageSize)?.map((item) => {
        return (
          <ProductClassificationItem productGroup={item} key={item.id} onClick={handleClick} />
        );
      })}
    </ScrollView>
  );
};

export { ProductClassification };
